package ui.windows;

import entities.PropertySys;
import entities.User;
import java.awt.Container;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import manager.DataManager;
import manager.GenericDriver;
import ui.panels.BlackPanel;
import ui.panels.DoctorsPanel;
import ui.panels.AdminSystemPanel;
import ui.panels.DepartmentHeadsPanel;
import ui.panels.ManagersPanel;
import ui.panels.AdminBusiPanel;
import ui.panels.StartPanel;

/**
 * 
 * @author viev
 * main frame of Remedy Scheduler aplication.
 */
public class RemedySchedulerFrame extends javax.swing.JFrame {

    /** Creates new form RemedySchedulerFrame */
    public RemedySchedulerFrame() {
        initComponents();
        this.setSize(950, 650);
        this.setLocationRelativeTo(null);
        try {
            boolean loaded = loadDataManager();
            if (loaded) {
            } else {
                JOptionPane.showMessageDialog(null, "Cannot connect to Database");
            }
        } catch (Exception e) {
        }
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(RemedySchedulerFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(RemedySchedulerFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(RemedySchedulerFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(RemedySchedulerFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        connected = false;
        login = false;
        miConnect.setEnabled(true);
        miDisconect.setEnabled(false);
    }

    /**
     * 
     * @return 
     * create a DataManager
     */
    private boolean loadDataManager() {
        try {
            dataManager = new DataManager();
            dataManager.loadProperties();
            return true;
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(RemedySchedulerFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    /**
     * 
     * @return 
     * get properties of application.
     */
    public PropertySys getSysProperties() {
        return dataManager.getSysProperties();
    }

    /**
     * set properties of application.
     */
    public void setProperties() {
        dataManager.setChangeConfig();
    }

    /**
     * 
     * @param username
     * @param password 
     * set username and password
     */
    public void setLogin(String username, String password) {
        dataManager.setUsername(username);
        dataManager.setPassword(password);
    }

    /**
     * 
     * @return 
     * connect to database
     */
    public boolean connect() {
        if (!connected) {
            connected = dataManager.connect();
            if (connected) {
                return true;
            } else {
                new Thread() {

                    @Override
                    public void run() {
                        JOptionPane.showMessageDialog(null, "Cannot connect to Database", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }.start();
            }
        }
        return false;
    }

    /**
     * show login dialog
     */
    public void showLoginDialog() {
        new Thread() {

            @Override
            public void run() {
                loginDialog.setVisible(true);
            }
        }.start();
    }

    /**
     * 
     * @return 
     * method to disconnect.
     */
    public boolean disconnect() {
        if (connected) {
            connected = !dataManager.disConnect();
            if (!connected) {
                miConnect.setEnabled(true);
                miDisconect.setEnabled(false);
                login = false;
                return true;
            }
        }
        return false;
    }

    /**
     * disconnect action
     */
    public void disconnectAction() {
        if (connected) {
            if (disconnect()) {
                this.getContentPane().removeAll();
                this.repaint();
                this.add(new StartPanel());
                this.revalidate();
                this.setTitle("Remedy Scheduler");
                this.setVisible(true);
            } else {
                JOptionPane.showMessageDialog(null, "Cannot disconnect !", "Error", JOptionPane.WARNING_MESSAGE);
            }
        }
    }

    /**
     * 
     * @return 
     * method used to login
     */
    public boolean login() {
        if (connected) {
            if (!login) {
                login = dataManager.login();
                if (login) {
                    miConnect.setEnabled(false);
                    miDisconect.setEnabled(true);
                    loginDialog.setVisible(false);
                    designComponets();
                    loginDialog.getLoadDialog().setVisible(false);
                } else {
                    new Thread() {

                        @Override
                        public void run() {
                            JOptionPane.showMessageDialog(null, "Username or passwrod is incorrect !");
                        }
                    }.start();
                }
                return login;
            }
        }
        return false;
    }

    /**
     * 
     * @return 
     * method used to logout
     */
    public boolean logout() {
        if (login) {
            login = !dataManager.logout();
            if (!login) {
                this.setVisible(false);
                designComponets();
                this.setVisible(true);
                return true;
            }
            return login;
        }
        return false;
    }

    /**
     * method used to disgn componets of frame after login,
     */
    public void designComponets() {
        int indexObject = dataManager.getIndexObject();
        Object switchPanel = null;
        switch (indexObject) {
            case 0:
                this.setTitle("Remedy Scheduler");
                switchPanel = new BlackPanel(this);
                break;
            case 1:
                this.setTitle("Remedy Scheduler - Manager");
                switchPanel = new ManagersPanel(this);
                break;
            case 2:
                this.setTitle("Remedy Scheduler - Administractor of System");
                switchPanel = new AdminSystemPanel(this);
                break;
            case 3:
                this.setTitle("Remedy Scheduler - Administractor of Bussiness");
                switchPanel = new AdminBusiPanel(this);
                break;
            case 4:
                this.setTitle("Remedy Scheduler - Departmental Head");
                switchPanel = new DepartmentHeadsPanel(this);
                break;
            case 5:
                this.setTitle("Remedy Schduler - Doctor");
                switchPanel = new DoctorsPanel(this);
                break;
        }
        Container container = this.getContentPane();
        container.removeAll();
        this.repaint();
        container.add((JPanel) switchPanel);
        this.revalidate();
    }

    /**
     * 
     * @return 
     * get user login
     */
    public User getUser() {
        return dataManager.getUser();
    }

    /**
     * 
     * @return 
     * Driver of user login.
     */
    public Object getDriver() {
        return dataManager.getDriver();
    }

    /**
     * 
     * @return GenericDriver
     */
    public GenericDriver getGenericDriver() {
        return dataManager.getGenericDriver();
    }

    private void showAbout() {
        AboutDialog dialog = new AboutDialog(this, true);
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
    }

    /**
     * exit application
     */
    public void exit() {
        try {
            dataManager.setChangeProperties();
            if (dataManager.isConnected()) {
                boolean disconnected = disconnect();
                if (!disconnected) {
                    JOptionPane.showMessageDialog(null, "Cannot disconnect !", "Error", JOptionPane.WARNING_MESSAGE);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.dispose();
        System.exit(0);
    }

    /**
     * 
     * @return connnected
     */
    public boolean isConnected() {
        return connected;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuBar1 = new javax.swing.JMenuBar();
        mOperation = new javax.swing.JMenu();
        miConnect = new javax.swing.JMenuItem();
        miDisconect = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        miExit = new javax.swing.JMenuItem();
        mHelp = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        jMenuItem2 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Remedy Scheduler");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jMenuBar1.setBackground(new java.awt.Color(204, 204, 204));
        jMenuBar1.setMinimumSize(new java.awt.Dimension(0, 10));

        mOperation.setText("Operation");

        miConnect.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        miConnect.setText("Connect...");
        miConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miConnectActionPerformed(evt);
            }
        });
        mOperation.add(miConnect);

        miDisconect.setText("Disconnect...");
        miDisconect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miDisconectActionPerformed(evt);
            }
        });
        mOperation.add(miDisconect);
        mOperation.add(jSeparator1);

        miExit.setText("Exit");
        miExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miExitActionPerformed(evt);
            }
        });
        mOperation.add(miExit);

        jMenuBar1.add(mOperation);

        mHelp.setText("Help");

        jMenuItem1.setText("View help");
        mHelp.add(jMenuItem1);
        mHelp.add(jSeparator2);

        jMenuItem2.setText("About");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        mHelp.add(jMenuItem2);

        jMenuBar1.add(mHelp);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
    exit();
}//GEN-LAST:event_formWindowClosing

private void miConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miConnectActionPerformed
    showLoginDialog();
}//GEN-LAST:event_miConnectActionPerformed

private void miDisconectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miDisconectActionPerformed
    disconnectAction();
}//GEN-LAST:event_miDisconectActionPerformed

private void miExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miExitActionPerformed
    exit();
}//GEN-LAST:event_miExitActionPerformed

private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
    showAbout();
}//GEN-LAST:event_jMenuItem2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(RemedySchedulerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(RemedySchedulerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(RemedySchedulerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(RemedySchedulerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                final RemedySchedulerFrame mainFrame = new RemedySchedulerFrame();
                mainFrame.add(new StartPanel());
                mainFrame.revalidate();
                mainFrame.setVisible(true);
                mainFrame.loginDialog = new LoginDialog(mainFrame, true);
                mainFrame.loginDialog.setLocationRelativeTo(null);
                new Thread() {

                    @Override
                    public void run() {
                        try {
                            sleep(500);
                            mainFrame.loginDialog.setVisible(true);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(RemedySchedulerFrame.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }.start();
            }
        });
    }
    private DataManager dataManager;
    private LoginDialog loginDialog;
    private boolean connected;
    private boolean login;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JMenu mHelp;
    private javax.swing.JMenu mOperation;
    private javax.swing.JMenuItem miConnect;
    private javax.swing.JMenuItem miDisconect;
    private javax.swing.JMenuItem miExit;
    // End of variables declaration//GEN-END:variables
}
